package com.ruoyi.wechat.util;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.wechat.domain.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class TokenUtil {

	@Autowired
	private ISysConfigService sysConfigService;

	private static Map<String, Token> tokenMap = new HashMap<String, Token>();
	/**
	*@Description: TODO(获取token) 
	* @author cuihang   
	*@date 2015-11-26 上午11:54:21 
	*@param APPKEY 
	*@param fefresh 是否重新获取，为true则强制重新获取
	*@return
	 */
	private  static int times=0;
	public Token getToken(String APPKEY, boolean fefresh) {
		if(null==APPKEY){
			Token token = new Token();
			token.setAccessToken("");
			System.out.println("error:getToken:APPKEY not null;");
			return token;
		}
		long sec = System.currentTimeMillis() / 1000;
		if (fefresh||null == tokenMap.get(APPKEY) || (sec - tokenMap.get(APPKEY).getExpiresIn()) > 3600) {
			String requestUrl = ConstantWeChat.TOKEN_URL.replace("#APPID#",sysConfigService.selectConfigByKey(APPKEY+"_APPKEY")).replace("#APPSECRET#", sysConfigService.selectConfigByKey(APPKEY+"_SECRET"));
			JSONObject jsonObject = CommonUtil.doGetURL(requestUrl);
			Token token = new Token();
			if (null != jsonObject) {
				String errcode=jsonObject.getString("errcode");
				if(null==errcode){
					token.setAccessToken(jsonObject.getString("access_token"));
					token.setExpiresIn(System.currentTimeMillis() / 1000);
					tokenMap.put(APPKEY, token);
					times=0;
				}else{
					//重新请求
					times++;
					System.out.println("error:getToken:"+errcode+jsonObject.getString("errmsg"));
					if(times<=3){
						return getToken(APPKEY,fefresh);
					}
					times=0;

				}

			}
		}
		return tokenMap.get(APPKEY);
	}
	public Token getToken(String APPKEY){
		return getToken(APPKEY, false);
	}

}
